package com.edu.controller;

import com.edu.entity.UcenterMember;
import com.edu.service.UcenterMemberService;
import com.edu.utils.ConstantWxUtils;
import com.edu.utils.HttpClientUtils;
import com.edu.utils.JwtUtils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @author 麦翔盛
 * @description: 微信登录控制类
 * @date 2021/11/13 18:24
 */
@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxController {
    @Autowired
    private UcenterMemberService ucenterMemberService;

    /**
     * 返回用户信息
     *
     * @param code
     * @param state
     * @return
     */
    @GetMapping("/callback")
    public String callback(String code, String state) {
        //拼接向认证服务器发送请求换取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code);
        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //解析json字符串
        Gson gson = new Gson();
        //转换为hashMap
        HashMap<String, String> resultMap = gson.fromJson(result, HashMap.class);
        //从map中获取access_token和openid
        String accessToken = resultMap.get("access_token");
        String openId = resultMap.get("openid");
        System.out.println("accessToken:" + accessToken);
        System.out.println("openid:" + openId);


        //判断数据库中是否有该用户
        UcenterMember member = ucenterMemberService.getMemberByOpenId(openId);

        if (member == null) {
            //如果数据库中没有该微信id就将这个账号放到数据库中
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl,
                    accessToken,
                    openId);
            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //将json字符串转换为hashMap
            HashMap<String, String> userInfoMap = gson.fromJson(resultUserInfo, HashMap.class);
            //获取用户昵称和用户头像
            String nickname = userInfoMap.get("nickname");
            String headimgurl = userInfoMap.get("headimgurl");
            member = new UcenterMember();
            member.setAvatar(headimgurl);
            member.setNickname(nickname);
            member.setOpenid(openId);
            ucenterMemberService.save(member);
        }
        //使用jwt工具类生成token字符串
        String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        //通过路径传递token字符串
        return "redirect:http://localhost:3000?token=" + jwtToken;
    }


    /**
     * 微信登录，生成二维码
     *
     * @return
     */
    @GetMapping("/login")
    public String login() {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //取出地址，并进行base64编码
        String redirect_url = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            String encode = URLEncoder.encode(redirect_url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //将地址中的%s值填充
        String url = String.format(baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirect_url,
                "mxs");
        //重定向到微信登录界面
        return "redirect:" + url;
    }

}







